import React, { useState } from "react";
import { Button, Typography } from "antd";
import markdownit from "markdown-it";
import { useWorkareaStyle } from "./styles";
import ProductViewer from "./ProductViewer";
import SaveContentModal from "./SaveContentModal";
import { FlightOption } from "../../services/apiService";
import { FlightState } from "./types";
import { useTranslation } from 'react-i18next';

// 配置 markdown-it 以支持 HTML 和更好的渲染
const md = markdownit({
  html: true, // 允许 HTML 标签
  breaks: true, // 转换换行符
  linkify: true, // 自动转换链接
  typographer: true, // 启用一些语言中性的替换 + 引号美化
});

interface WorkAreaProps {
  copilotOpen: boolean;
  setCopilotOpen: (open: boolean) => void;
  displayHtml: string;
  displayProductId: string;
  flightState?: FlightState;
  currentDisplayType?: "html" | "product" | null;
  onContentSaved?: (productId: string) => void;
}

// 处理HTML中的链接，为外部链接添加target="_blank"和rel="noopener noreferrer"
const processHtmlLinks = (html: string): string => {
  if (!html) return html;
  
  // 先处理Markdown格式的链接，将其转换为HTML链接
  // 匹配Markdown链接格式: [text](url)
  let processedHtml = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (match, text, url) => {
    // 检查是否为锚点链接
    if (url.startsWith('#')) {
      return `<a href="${url}">${text}</a>`;
    } else {
      return `<a href="${url}" target="_blank" rel="noopener noreferrer">${text}</a>`;
    }
  });
  
  // 创建一个临时的div来解析HTML
  const tempDiv = document.createElement('div');
  tempDiv.innerHTML = processedHtml;
  
  // 查找所有未处理的<a>标签（可能直接以HTML形式存在的链接）
  const links = tempDiv.querySelectorAll('a');
  
  links.forEach(link => {
    const href = link.getAttribute('href');
    // 检查是否为外部链接（非锚点链接）
    if (href && !href.startsWith('#') && !link.hasAttribute('target')) {
      link.setAttribute('target', '_blank');
      link.setAttribute('rel', 'noopener noreferrer');
    }
  });
  
  return tempDiv.innerHTML;
};

const WorkArea: React.FC<WorkAreaProps> = ({
  copilotOpen,
  setCopilotOpen,
  displayHtml,
  displayProductId,
  flightState,
  currentDisplayType,
  onContentSaved,
}) => {
  const { styles } = useWorkareaStyle();
  const [saveModalVisible, setSaveModalVisible] = useState(false);
  const { flightInfo, flightList } = flightState || {};
  const { t } = useTranslation();
  
  // 处理保存成功
  const handleSaveSuccess = (productId: string) => {
    setSaveModalVisible(false);
    if (onContentSaved) {
      onContentSaved(productId);
    }
  };

  // 判断是否是HTML内容还是URL
  const isHtmlContent = displayHtml && !displayHtml?.startsWith?.("http");

  // 根据 currentDisplayType 和可用内容决定显示什么
  const getDisplayContent = () => {
    // 如果有明确的显示类型指示
    if (currentDisplayType === "product" && displayProductId) {
      return {
        type: "product",
        title: t('workarea.productDetail'),
        content: <ProductViewer 
          productId={displayProductId}
          flightState={flightState}
        />,
      };
    }

    if (currentDisplayType === "html" && displayHtml) {
      return {
        type: "html",
        title: isHtmlContent ? t('workarea.flowContentPreview') : t('workarea.urlPreview'),
        showSaveButton: isHtmlContent, // 只有 HTML 内容才显示保存按钮
        content: isHtmlContent ? (
          <Typography
            style={{
              width: "100%",
              height: "100%",
              overflow: "auto",
              padding: 16,
              backgroundColor: "#fff",
            }}
          >
            <div dangerouslySetInnerHTML={{ __html: processHtmlLinks(md.render(displayHtml)) }} />
          </Typography>
        ) : (
          <iframe
            src={displayHtml}
            style={{ width: "100%", height: "100%", border: "none" }}
            title="Display HTML"
          />
        ),
      };
    }

    // 如果没有明确指示，按优先级显示
    if (displayProductId) {
      return {
        type: "product",
        title: t('workarea.productDetail'),
        content: <ProductViewer 
          productId={displayProductId}
          flightState={flightState}
        />,
      };
    }

    if (displayHtml) {
      return {
        type: "html",
        title: isHtmlContent ? t('workarea.flowContentPreview') : t('workarea.urlPreview'),
        showSaveButton: isHtmlContent, // 只有 HTML 内容才显示保存按钮
        content: isHtmlContent ? (
          <Typography
            style={{
              width: "100%",
              height: "100%",
              overflow: "auto",
              padding: 16,
              backgroundColor: "#fff",
            }}
          >
            <div dangerouslySetInnerHTML={{ __html: md.render(processHtmlLinks(displayHtml)) }} />
          </Typography>
        ) : (
          <iframe
            src={displayHtml}
            style={{ width: "100%", height: "100%", border: "none" }}
            title="Display HTML"
          />
        ),
      };
    }

    // 默认空状态
    return {
      type: "empty",
      title: t('workarea.title'),
      content: (
        <div
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            height: "100%",
            color: "#999",
          }}
        >
          {t('workarea.noContent')}
        </div>
      ),
    };
  };

  const displayContent = getDisplayContent();

  return (
    <div className={styles.workarea}>
      <div className={styles.workareaHeader}>
        <div className={styles.headerTitle}>
          <span>{displayContent.title}</span>
        </div>

        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          {displayContent.showSaveButton && (
            <Button
              type="primary"
              size="small"
              onClick={() => setSaveModalVisible(true)}
            >
              {t('workarea.saveStrategy')}
            </Button>
          )}

          {!copilotOpen && (
            <div
              onClick={() => setCopilotOpen(true)}
              className={styles.headerButton}
            >
              ✨ {t('workarea.aiAssistant')}
            </div>
          )}
        </div>
      </div>

      <div
        className={styles.workareaBody}
        style={{ margin: copilotOpen ? 16 : "16px 48px" }}
      >
        <div className={styles.bodyContent}>{displayContent.content}</div>
      </div>

      {/* 保存内容弹窗 */}
      <SaveContentModal
        visible={saveModalVisible}
        htmlContent={displayHtml}
        onCancel={() => setSaveModalVisible(false)}
        onSuccess={handleSaveSuccess}
      />
    </div>
  );
};

export default WorkArea;